"""
任务选择对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                           QPushButton, QWidget, QTableWidget, QTableWidgetItem,
                           QCheckBox, QHeaderView, QComboBox)
from PyQt6.QtCore import Qt, pyqtSignal
from com.db.task_manager import TaskManager
import json


class TagComboBox(QComboBox):
    """标签选择器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setEditable(False)
        self.setMaximumWidth(150)
        self.addItem("全部", None)
        
    def set_tags(self, tags_list):
        """设置标签列表"""
        self.clear()
        self.addItem("全部", None)
        for tag in tags_list:
            self.addItem(tag, tag)


class TaskDialog(QDialog):
    """任务选择对话框"""
    
    selection_changed = pyqtSignal(list)
    
    def __init__(self, parent=None, selected_ids=None):
        super().__init__(parent)
        self.setWindowTitle("选择任务")
        self.resize(800, 600)
        
        self.task_manager = TaskManager()
        self.selected_ids = selected_ids or []
        self.row_checkboxes = []  # 初始化复选框列表
        self.setup_ui()
        self.load_data()  # 加载数据

    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 顶部操作区域
        top_layout = QHBoxLayout()
        
        # 标签选择器
        self.tag_selector = TagComboBox()
        self.tag_selector.currentIndexChanged.connect(self.on_tag_changed)
        top_layout.addWidget(self.tag_selector)
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        
        # 设置表头
        self.table.setHorizontalHeaderLabels(["", "ID", "商品名称", "标签", "价格"])
        
        # 设置表格样式
        header = self.table.horizontalHeader()
        header.setStyleSheet("""
            QHeaderView::section { 
                padding: 0 5px;
                background-color: #f5f5f5;
            }
        """)
        header.setFixedHeight(40)
        
        # 设置列宽
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        header.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)
        
        self.table.setColumnWidth(0, 50)  # 复选框列
        self.table.setColumnWidth(1, 80)  # ID列
        self.table.setColumnWidth(4, 100)  # 价格列
        
        # 创建表头复选框容器
        header_widget = QWidget()
        header_layout = QHBoxLayout(header_widget)
        header_layout.setContentsMargins(0, 0, 0, 0)
        header_layout.setSpacing(0)
        header_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 创建表头复选框
        self.header_checkbox = QCheckBox()
        self.header_checkbox.setStyleSheet("""
            QCheckBox {
                margin: 0;
                padding: 0;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }
            QCheckBox::indicator:unchecked {
                border: 1px solid #d9d9d9;
                background-color: white;
            }
            QCheckBox::indicator:checked {
                border: 1px solid #1890ff;
                background-color: #1890ff;
            }
        """)
        self.header_checkbox.clicked.connect(self.on_header_checkbox_changed)
        header_layout.addWidget(self.header_checkbox)
        
        # 设置表头第一列的widget
        header_widget.setFixedSize(50, 40)
        header_widget.setParent(header)
        header_widget.move(header.sectionPosition(0), 0)
        header_widget.show()
        
        # 隐藏垂直表头
        self.table.verticalHeader().setVisible(False)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        self.confirm_btn = QPushButton("确定")
        self.confirm_btn.clicked.connect(self.accept)
        
        button_style = """
            QPushButton {
                padding: 8px 16px;
                font-size: 14px;
                border-radius: 4px;
            }
        """
        
        self.cancel_btn.setStyleSheet(button_style + """
            QPushButton {
                background-color: white;
                border: 1px solid #d9d9d9;
                color: rgba(0, 0, 0, 0.85);
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
        """)
        
        self.confirm_btn.setStyleSheet(button_style + """
            QPushButton {
                background-color: #1890ff;
                border: none;
                color: white;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        
        button_layout.addStretch()
        button_layout.addWidget(self.cancel_btn)
        button_layout.addWidget(self.confirm_btn)
        
        layout.addLayout(top_layout)
        layout.addWidget(self.table)
        layout.addLayout(button_layout)

    def load_data(self, tasks=None):
        """加载数据"""
        print("开始加载数据...")
        
        # 清空表格和复选框列表
        self.table.setRowCount(0)
        self.row_checkboxes.clear()
        
        # 如果没有传入任务列表，则获取所有任务
        if tasks is None:
            tasks = self.task_manager.get_active_tasks()
            
            # 收集所有标签
            all_tags = set()
            for task in tasks:
                if task.get('tags'):
                    tags = task['tags']
                    if isinstance(tags, str):
                        try:
                            tags = json.loads(tags)
                        except json.JSONDecodeError:
                            continue
                    if isinstance(tags, list):
                        all_tags.update(tags)
                        
            # 更新标签选择器
            self.tag_selector.set_tags(sorted(all_tags))
        
        if not tasks:
            return
            
        self.table.setRowCount(len(tasks))
        print(f"共加载 {len(tasks)} 条数据")
        
        for row, task in enumerate(tasks):
            print(f"\n处理第 {row + 1} 行数据:")
            
            # 添加复选框到容器中
            checkbox = QCheckBox()
            checkbox.setChecked(task['id'] in self.selected_ids)
            self.row_checkboxes.append(checkbox)
            
            checkbox.setStyleSheet("""
                QCheckBox {
                    margin: 0;
                    padding: 0;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #d9d9d9;
                    background-color: white;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #1890ff;
                    background-color: #1890ff;
                }
            """)
            
            checkbox.clicked.connect(self.on_row_checkbox_changed)
            
            # 创建容器并设置布局
            container = QWidget()
            layout = QHBoxLayout(container)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(0)
            layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            layout.addWidget(checkbox)
            
            # 设置单元格内容
            self.table.setCellWidget(row, 0, container)
            self.table.setItem(row, 1, QTableWidgetItem(str(task['id'])))
            self.table.setItem(row, 2, QTableWidgetItem(task['name']))
            
            # 处理标签
            tags = task.get('tags', [])
            if isinstance(tags, str):
                try:
                    tags = json.loads(tags)
                except json.JSONDecodeError:
                    tags = []
            self.table.setItem(row, 3, QTableWidgetItem(", ".join(tags) if tags else ""))
            
            # 处理价格
            price = task.get('sell_min_price', 0)
            self.table.setItem(row, 4, QTableWidgetItem(f"{price:.2f}" if price is not None else "-"))
        
        # 重置表头复选框状态
        self.header_checkbox.setChecked(False)
        self.on_row_checkbox_changed()  # 更新表头状态

    def on_header_checkbox_changed(self):
        """表头复选框状态改变"""
        state = self.header_checkbox.checkState()
        print(f"\n表头复选框状态改变，当前状态: {state}")
        
        # 只在完全选中或完全未选中时改变行复选框状态
        if state != Qt.CheckState.PartiallyChecked:
            checked = (state == Qt.CheckState.Checked)
            # 阻止行复选框的信号
            for checkbox in self.row_checkboxes:
                checkbox.blockSignals(True)
                checkbox.setChecked(checked)
                checkbox.blockSignals(False)
                print(f"设置复选框状态: {checked}")
        
        print("\n表头复选框处理完成")

    def on_row_checkbox_changed(self):
        """行复选框状态改变"""
        print("\n行复选框状态改变")
        
        # 检查所有复选框的状态
        checked_count = sum(1 for cb in self.row_checkboxes if cb.isChecked())
        total_count = len(self.row_checkboxes)
        
        print(f"选中数量: {checked_count}, 总数: {total_count}")
        
        # 阻止表头复选框的信号
        self.header_checkbox.blockSignals(True)
        
        # 根据选中情况设置表头复选框状态
        if checked_count == 0:
            # 没有选中任何项
            self.header_checkbox.setCheckState(Qt.CheckState.Unchecked)
            print("设置表头为未选中状态")
        elif checked_count == total_count:
            # 选中所有项
            self.header_checkbox.setCheckState(Qt.CheckState.Checked)
            print("设置表头为全选状态")
        else:
            # 部分选中
            self.header_checkbox.setCheckState(Qt.CheckState.PartiallyChecked)
            print("设置表头为部分选中状态")
        
        self.header_checkbox.blockSignals(False)
        print("行复选框状态处理完成")

    def on_tag_changed(self, index):
        """处理标签选择改变"""
        selected_tag = self.tag_selector.currentData()
        if selected_tag:
            # 获取启用状态的任务并按标签筛选
            tasks = self.task_manager.search_tasks(tags=[selected_tag], status=1)
        else:
            # 获取所有启用状态的任务
            tasks = self.task_manager.get_active_tasks()
        self.load_data(tasks)

    def get_selected_tasks(self):
        """获取选中的任务列表"""
        print("\n开始获取选中的任务")
        selected = []
        
        # 使用保存的复选框引用
        for row, checkbox in enumerate(self.row_checkboxes):
            print(f"\n检查第 {row + 1} 行:")
            if checkbox.isChecked():
                # 获取单元格内容并进行验证
                id_item = self.table.item(row, 1)
                name_item = self.table.item(row, 2)
                
                if id_item is None or name_item is None:
                    print(f"警告：第 {row + 1} 行数据不完整，跳过")
                    continue
                    
                try:
                    task_id = int(id_item.text())
                    task_name = name_item.text()
                    selected.append({
                        'id': task_id,
                        'name': task_name
                    })
                    print(f"添加选中的任务: ID={task_id}, 名称={task_name}")
                except (ValueError, AttributeError) as e:
                    print(f"警告：第 {row + 1} 行数据格式错误：{str(e)}")
                    continue
            else:
                print("复选框未选中")
        
        print(f"\n共找到 {len(selected)} 个选中的任务")
        return selected

    def accept(self):
        """确认选择"""
        try:
            selected_tasks = self.get_selected_tasks()
            if selected_tasks:
                self.selection_changed.emit(selected_tasks)
            super().accept()
        except Exception as e:
            print(f"错误：获取选中任务失败：{str(e)}")
            super().reject()
